package com.code.configs.thread;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author xiaoyaowang
 */
@Configuration
@EnableConfigurationProperties(TreadPoolConfig.TreadPoolProperties.class)
@AutoConfigureAfter(TreadPoolConfig.TreadPoolProperties.class)
@EnableAsync
@EnableScheduling
@Slf4j
public class TreadPoolConfig implements SchedulingConfigurer, AsyncConfigurer {

    @Resource
    private TreadPoolProperties treadPoolProperties;

    /**
     * 定时任务使用的线程池
     *
     * @return 定时任务的线程池
     */
    @Bean(destroyMethod = "shutdown", name = "taskScheduler")
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(treadPoolProperties.getCoreSize());
        scheduler.setThreadNamePrefix("schedule-task-");
        scheduler.setAwaitTerminationSeconds(treadPoolProperties.getAwaitTerminationSeconds());
        scheduler.setWaitForTasksToCompleteOnShutdown(treadPoolProperties.getWaitForTasksToCompleteOnShutdown());
        return scheduler;
    }

    /**
     * 异步任务执行线程池
     *
     * @return 异步任务线程池
     */
    @Bean(name = "asyncExecutor")
    public ThreadPoolTaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(treadPoolProperties.getCoreSize());
        executor.setQueueCapacity(treadPoolProperties.getBlockQueueSize());
        executor.setKeepAliveSeconds(treadPoolProperties.getActiveTime());
        executor.setMaxPoolSize(treadPoolProperties.getMaxSize());
        executor.setThreadNamePrefix("asyncTaskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = taskScheduler();
        scheduledTaskRegistrar.setTaskScheduler(taskScheduler);
    }

    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> log.error("异步任务执行出现异常, message {}, emthod {}, params {}", throwable, method, objects);
    }

    /**
     * 读取线程池相关的属性的类
     *
     * @author xiaoyaowang
     */
    @ConfigurationProperties(prefix = "thread.pool")
    @Getter
    @Setter
    static class TreadPoolProperties {
        private Integer coreSize;
        private Integer maxSize;
        private Integer activeTime;
        private Integer blockQueueSize;
        private Integer awaitTerminationSeconds;
        private Boolean waitForTasksToCompleteOnShutdown;
    }

}
